﻿using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace nsadv.Statistic.TestDataParser
{
	class Program
	{
		static void Main(string[] args)
		{
			string testDataFileName = ConfigurationManager.AppSettings["TestDataFileName"];
			string serviceUrl = ConfigurationManager.AppSettings["ServiceUrl"];

			FileInfo fi = new FileInfo(testDataFileName);
			using (var reader = fi.OpenText())
			{
				var xmlData = new StringBuilder();
				bool writeToData = false;
				while (!reader.EndOfStream)
				{
					string dataLine = reader.ReadLine();

					// 1. Ищем === StatisticsBody === - начало чтения данных
					if (dataLine.Contains("=== StatisticsBody ==="))
					{
						xmlData.Clear();
						writeToData = true;
						continue;
					}

					// 2. Ищем === End === - окончание чтения данных
					if (dataLine.Contains("=== End ==="))
					{
						writeToData = false;
						// Отправляем запрос
						try
						{
							SendStatRequest(serviceUrl, xmlData.ToString().Replace(@"\", string.Empty));
						}
						catch (Exception ex)
						{
							Console.WriteLine(ex.Message);
						}
						continue;
					}

					if (writeToData)
					{
						xmlData.Append(dataLine);
					}

				}
			}

		}

		private static void SendStatRequest(string serviceUrl, string xmlData)
		{
			// prepear data
			ASCIIEncoding encoding = new ASCIIEncoding();
			string postData = "p=" + xmlData;
			postData = postData + "&errors=true";
			byte[] data = encoding.GetBytes(postData);

			// prepare request
			var request = (HttpWebRequest)WebRequest.Create(serviceUrl);
			request.Method = "POST";
			request.ContentType = "application/x-www-form-urlencoded";
			request.ContentLength = data.Length;
			using (var stream = request.GetRequestStream())
			{
				stream.Write(data, 0, data.Length);
				try
				{
					var response = (HttpWebResponse)request.GetResponse();
					Console.WriteLine(response.StatusCode);
				}
				catch (HttpException e)
				{
					Console.WriteLine(e.GetHtmlErrorMessage());
				}
			}
		}
	}
}
